package com.yj.web.WeChat.service;

import com.yj.web.WeChat.Bean.WxUser;
import com.yj.web.WeChat.Message.WxXmlMessage;
import com.yj.web.WeChat.Message.WxXmlOutMessage;
import com.yj.web.WeChat.api.WxMessageRouter;
import com.yj.web.WeChat.api.WxService;
import com.yj.web.WeChat.handler.*;
import com.yj.web.dao.mapper.IntroducerMapper;
import com.yj.web.dao.po.admin.Introducer;
import com.yj.web.util.WxErrorException;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Set;

//import sun.rmi.log.LogHandler;

/**
 * Created by yanlinyang on 2017/9/10.
 */
@Service("wxCoreService")
public class WxCoreServiceImpl implements WxCoreService {
    @Autowired
    protected WxService wxService;
    @Autowired
    protected LogHandler logHandler;
    @Autowired
    protected SubscribeHandler subscribeHandler;
    @Autowired
    protected ScanHandler scanHandler;
    @Autowired
    protected ClickHandler clickHandler;
    @Autowired
    protected ViewHandler viewHandler;

    @Autowired
    private IntroducerMapper introducerMapper;
//    @Autowired
//    protected MsgHandler msgHandler;

    protected Logger logger = LoggerFactory.getLogger(getClass());
    private WxMessageRouter router;

    @PostConstruct
    public void init() {
        this.refreshRouter();
    }

    @Override
    public void requestGet(String urlWithParams) throws IOException {
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        HttpGet httpget = new HttpGet(urlWithParams);
        httpget.addHeader("Content-Type", "text/html;charset=UTF-8");
        //配置请求的超时设置
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(50)
                .setConnectTimeout(50)
                .setSocketTimeout(50).build();
        httpget.setConfig(requestConfig);

        CloseableHttpResponse response = httpclient.execute(httpget);
        System.out.println("StatusCode -> " + response.getStatusLine().getStatusCode());

        HttpEntity entity = response.getEntity();
        String jsonStr = EntityUtils.toString(entity);
        System.out.println(jsonStr);

        httpget.releaseConnection();
    }

    @Override
    public void requestPost(String url, List<NameValuePair> params) throws ClientProtocolException, IOException {
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();

        HttpPost httppost = new HttpPost(url);
        httppost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));

        CloseableHttpResponse response = httpclient.execute(httppost);
        System.out.println(response.toString());

        HttpEntity entity = response.getEntity();
        String jsonStr = EntityUtils.toString(entity, "utf-8");
        System.out.println(jsonStr);

        httppost.releaseConnection();
    }

    @Override
    public void refreshRouter() {
        final WxMessageRouter newRouter = new WxMessageRouter(this.wxService);
        // 记录所有事件的日志
        newRouter.rule().handler(this.logHandler).next();
        // 关注事件
        newRouter.rule().async(false).msgType("event")
                .event("subscribe").handler(this.subscribeHandler)
                .end();
        //扫描事件
        newRouter.rule().async(false).msgType("event")
                .event("SCAN").handler(this.scanHandler)
                .end();
        //点击事件
        newRouter.rule().async(false).msgType("event")
                .event("CLICK").handler(this.clickHandler)
                .end();
        //点击事件
        newRouter.rule().async(false).msgType("event")
                .event("VIEW").handler(this.viewHandler)
                .end();
        // 默认,转发消息给客服人员
//        newRouter.rule().async(false).handler(this.msgHandler).end();
        this.router = newRouter;
    }

    @Override
    public WxXmlOutMessage route(WxXmlMessage inMessage) {
        try {
            return this.router.route(inMessage);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }
        return null;
    }

    @Override
    public WxUser getUserInfo(String openid, String lang) {
        WxUser wxMpUser = null;
        try {
            wxMpUser = this.wxService.userInfo(openid, lang);
        } catch (WxErrorException e) {
            this.logger.error(e.getError().toString());
        }
        return wxMpUser;
    }

    public void checkOpenId(WxXmlMessage wxMessage) {
        String introducerId = wxMessage.getEventKey();
        introducerId = introducerId.replaceAll("qrscene_","");
        Introducer introducer = introducerMapper.findIntroducerById(Integer.parseInt(introducerId));

        String openId = wxMessage.getFromUser();
        String intro_phone = introducer.getPhone();
        Set<String> openIds = introducerMapper.getAllOpenIds();
        if (openIds.contains(openId)) {
            introducerMapper.updateFans(openId, intro_phone);
        } else {
            introducerMapper.insertFans(openId, intro_phone);
        }
    }

}
